package com.blockmeta.bbs.businesslibrary.util;

import com.blockmeta.bbs.businesslibrary.websocket.Market;

import java.util.Locale;

/**
 * @author AirThor
 * @date 2019/7/4.
 */
public class Format2Util {
    public static String longToHumanReadableFormat(long nNumber, int digit, String minSign) {
        return longToHumanReadableFormat(nNumber, digit, minSign, true);
    }

    public static String longToHumanReadableFormat(long nNumber, int digit, String minSign, boolean isCheckpMarket) {
        if (isCheckpMarket) {
            if (!Market.AppMarket.getAppMarket("").isHumanReadableFormatEnabled()) {
                return String.valueOf(nNumber);
            }
        }

        long tNumber = nNumber;

        if (tNumber < 0) {
            tNumber = Math.abs(nNumber);
        }
        int unit = 1000;
        int value = 1000;
        if (minSign.equals("M")) {
            value = 1000000;
        } else if (minSign.equals("B")) {
            value = 1000000000;
        }

        if (tNumber < value) {
            return String.valueOf(nNumber);
        }
        int exp = (int) (Math.log(tNumber) / Math.log(unit));
        String pre = String.valueOf("KMBTPE".charAt(exp - 1));
        double num = tNumber / Math.pow(unit, exp);
        String format = (num * unit % unit) == 0.0 ? "%.0f" : "%." + digit + "f";
        if (nNumber < 0) {
            format = "-" + format;
        }
        return removeTrailZero(String.format(Locale.ENGLISH, format, num)) + pre;
    }
    public static String doubleToHumanReadableFormat(double pNumber, int digit) {
        if (!Market.AppMarket.getAppMarket("").isHumanReadableFormatEnabled()) {
            return String.format(Locale.ENGLISH, "%." + digit + "f", pNumber);
        }

        double tNumber = pNumber;

        if (tNumber < 0) {
            tNumber = Math.abs(pNumber);
        }
        int unit = 1000;
        if (tNumber < unit) {
            return String.format(Locale.ENGLISH, "%." + digit + "f", pNumber);
        }
        int exp = (int) (Math.log(tNumber) / Math.log(unit));
        String pre = String.valueOf("KMBTPE".charAt(exp - 1));
        double num = tNumber / Math.pow(unit, exp);
        String format = (num * unit % unit) == 0.0 ? "%.0f" : "%." + digit + "f";
        if (pNumber < 0) {
            format = "-" + format;
        }
        return removeTrailZero(String.format(Locale.ENGLISH, format, num)) + pre;
    }

    public static String removeTrailZero(String str) {
        int pos = str.lastIndexOf(".");

        if (pos < 0)
            return str;

        int count = 0;
        for (int ii = str.length() - 1; ii >= pos; ii--) {
            if (str.charAt(ii) == '0' || str.charAt(ii) == '.')
                count++;
            else
                break;
        }
        return str.substring(0, str.length() - count);
    }
}
